package com.ruoyi.my.utils.util.baidutranslationutil;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;

public class OauthTokenUtil {

//    private static final String APP_ID = "117638276";
//    private static final String API_KEY = "YCrXL3vb7HKie4HCF7Z9loRR";
//    private static final String SECURITY_KEY = "e5BadVvYtByzyEIJEIrQE1fpXfozQsrk";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    public static String getAccessToken(String apiKey,String securityKey,String tokenUrl) {
        try {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + apiKey
                    + "&client_secret=" + securityKey);
            Request request = new Request.Builder()
                    .url(tokenUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            assert response.body() != null;
            return new JSONObject(response.body().string()).getString("access_token");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
